package com.dic.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.dic.R;
import com.dic.adapter.Listadapter;
import com.dic.model.Dic;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;

public class DicActivity extends Activity implements OnGestureListener {
	private ListView list;
	private EditText wordtext;
	private List<Dic> curdiclist;
	private Dic curDic;
	private final String DATABASE_PATH = "/data/data/com.dic/databases/";
	private final String DATABASE_FILENAME = "english.db3";
	private SQLiteDatabase database;
	private Drawable mIconSearchClear;
	private GestureDetector detector;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.search_main_view);
		database = openDatabase();
		list = (ListView) findViewById(R.id.lv_list);
		wordtext = (EditText) findViewById(R.id.et_input);
		mIconSearchClear = getResources().getDrawable(R.drawable.txt_search_clear);
		wordtext.setCompoundDrawablesWithIntrinsicBounds(null, null, mIconSearchClear, null);

		wordtext.setOnTouchListener(txtSearch_OnTouch);
		wordtext.addTextChangedListener(textWatcher);
		list.setOnItemClickListener(new CustomDicClick());

		detector = new GestureDetector(this);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {

		detector.onTouchEvent(ev);
		return super.dispatchTouchEvent(ev);
	}

	private OnTouchListener txtSearch_OnTouch = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_UP:
				int curX = (int) event.getX();
				if (curX > v.getWidth() - 55 && !TextUtils.isEmpty(wordtext.getText())) {
					wordtext.setText("");
					wordtext.onTouchEvent(event);// call native handler
					list.setVisibility(8);

					return true;// consume touch even
				}
				break;
			}
			return false;
		}
	};

	class CustomDicClick implements AdapterView.OnItemClickListener {

		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			curDic = curdiclist.get(arg2);
			changepage();
		}
	}

	private void changepage() {
		database.close();
		Intent intent = new Intent(DicActivity.this, DicDetailActivity.class);
		intent.putExtra("dic", curDic);
		startActivity(intent);

	}

	private TextWatcher textWatcher = new TextWatcher() {
		@Override
		public void afterTextChanged(Editable s) {
			if (TextUtils.isEmpty(s)) {
				list.setVisibility(8);
				curDic = null;
			} else {
				list.setVisibility(0);
				getdata();

			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (!wordtext.getText().toString().equals("")) {
				list.setVisibility(0);
			} else {
				list.setVisibility(8);
				curDic = null;
			}

		}
	};

	public void getdata() {
		// 查找单词的SQL语句
		if (database == null || !database.isOpen()) {
			database = SQLiteDatabase.openOrCreateDatabase(DATABASE_PATH + DATABASE_FILENAME, null);
		}

		String sql = "select id, words, explain, bookmark from ENGLISH where words LIKE '" + wordtext.getText().toString() + "%'";
		Cursor cursor = database.rawQuery(sql, null);
		List<Dic> arrView = null;
		arrView = new ArrayList<Dic>();
		Dic dicitem = null;
		while (cursor.moveToNext()) {
			int index = 0;
			dicitem = new Dic();
			dicitem.setId(cursor.getInt(index++));
			dicitem.setWord(cursor.getString(index++));
			dicitem.setExplain(cursor.getString(index++));
			dicitem.setMark(cursor.getInt(index++));
			arrView.add(dicitem);
		}
		cursor.close();
		BaseAdapter dicAdaptar = new Listadapter(arrView, DicActivity.this);
		list.setAdapter(dicAdaptar);
		curdiclist = arrView;

	}

	private SQLiteDatabase openDatabase() {
		// get dictionary.db3 path
		String databaseFilename = DATABASE_PATH + DATABASE_FILENAME;
		File dir = new File(DATABASE_PATH);
		// if  /data/data/com.dic/databases/  is exist create it 
		if (!dir.exists()) {
			dir.mkdir();
		}
		// if /data/data/com.dic/databases/dictionary.db3 not exist copy from res\raw\dictionary.db3 

		if (!(new File(databaseFilename)).exists()) {
			try {
				copyDataBase();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// open /data/data/com.dic/databases/dictionary.db3
		SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
		return database;
	}

	private void copyDataBase() throws IOException {

		// Open your local db as the input stream
		// File file = new File(Environment.getExternalStorageDirectory(),
		// DATABASE_NAME);

		InputStream myInput = getResources().openRawResource(R.raw.english);

		// Path to the just created empty db
		String outFileName = DATABASE_PATH + DATABASE_FILENAME;

		// Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);
		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}

		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();

	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		// TODO Auto-generated method stub

		TabHost mTabHost = (((TabActivity) getParent()).getTabHost());
		int tabId = mTabHost.getCurrentTab();

		if (Math.abs(e1.getY() - e2.getY()) > 100) {
			// Toast.makeText(context, "WRONG!!!!", Toast.LENGTH_LONG).show();
			return false;
		}

		if ((e1.getX() - e2.getX()) > 50 && Math.abs(velocityX) > 100) {
			// Toast.makeText(context, "To Right!!!!", Toast.LENGTH_LONG).show();
			if (tabId == 0 || tabId == 1) {
				tabId++;
			}

		} else if ((e2.getX() - e1.getX()) > 50 && Math.abs(velocityX) > 100) {
			// Toast.makeText(context, "To Left!!!!", Toast.LENGTH_LONG).show();
			if (tabId == 2 || tabId == 1) {
				tabId--;
			}
		}
		mTabHost.setCurrentTab(tabId);

		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

}